using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class RandomEngine : MonoBehaviour
{
    private static RandomEngine _instance;
    public static RandomEngine Instance {  get {  return _instance; } }

    private const int _randomSeedLength = 15;
    private string _randomSeed = null;

    // 使用C#的Random类来创建多个random对象
    // 为不同的需求生成相互独立的随机序列
    // 这个名称暂时先使用combatReward, 这个类可能需要与游戏逻辑屏蔽, 只用数组存储
    private System.Random _combatRewardRand;

    public void InitOnRunStart()
    {
        if (_randomSeed == null)
        {
            GenerateRandomSeed();
        }

        SetIndieRandomSeed();
    }

    private void GenerateRandomSeed()
    {
        Random.InitState((int)System.DateTime.Now.Ticks);
        string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        for (int i = 0; i < _randomSeedLength; i++)
        {
            _randomSeed += characters[Random.Range(0, characters.Length)];
        }
    }

    private void SetIndieRandomSeed()
    {
        // 为每个不同的随机数获取需求创建独立的random object
        // 每个random object用的range可能需要用一个表配置, 这里先直接用常数了
        _combatRewardRand = SetRandomSeedUsingRange(0, 3);
    }

    private System.Random SetRandomSeedUsingRange(int begin, int end)
    {
        int seedInt = 0;
        for (int i = begin; i < end; i++)
        {
            seedInt += 10 * (int)_randomSeed[i];
        }
        return new System.Random(seedInt);
    }


    public void SetRandomSeed(string seed)
    {
        if(_randomSeed != null)
        {
            Debug.Log("Run Has Started");
        }
        else
        {
            _randomSeed = seed;
        }
    }

    // 只负责返回固定的随机值, 由调用者处理获取到的随机值
    public int GetRandCombatRewards(int begin, int end)
    {
        return _combatRewardRand.Next(begin, end);
    }

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
    }
}
